var _ = require('lodash');
const Crypto = require('crypto-js');

export default class ProtocolSignUtils {
    static validSign(data, partner_key) {
        if (!data || !data.sign) {
            return true;
        }

        let queryString = Object.keys(data).filter(function(key) {
            return data[key] !== undefined && data[key] !== '' && ['sign', 'key'].indexOf(key) < 0;
        }).sort().map(function(key) {
            if (_.isObjectLike(data[key])) {
                return key + "=" + JSON.stringify(data[key]);
            } else {
                return key + "=" + data[key];
            }
        }).join("&") + "&key=" + partner_key;

        return (Crypto.SHA256(queryString).toString(Crypto.enc.Hex).toUpperCase() === data?.sign?.toUpperCase());
    }

    static getSignString(data, partner_key) {
        let queryString = Object.keys(data).filter(function(key) {
            return data[key] !== undefined && data[key] !== '' && ['sign', 'key'].indexOf(key) < 0;
        }).sort().map(function(key) {
            if (_.isObjectLike(data[key])) {
                return key + "=" + JSON.stringify(data[key]);
            } else {
                return key + "=" + data[key];
            }
        }).join("&") + "&key=" + partner_key;

        return Crypto.SHA256(queryString).toString(Crypto.enc.Hex).toUpperCase();
    }
}